import numpy as np

def circle_fit(x, y):
    n = len(x)
    # 计算各项系数
    sum_x = np.sum(x)
    sum_y = np.sum(y)
    sum_x2 = np.sum(x ** 2)
    sum_y2 = np.sum(y ** 2)
    sum_xy = np.sum(x * y)
    z = x ** 2 + y ** 2
    sum_xz = np.sum(x * z)
    sum_yz = np.sum(y * z)
    sum_z = np.sum(z)

    # 构建系数矩阵 A 和常数矩阵 B
    A = np.array([[sum_x2, sum_xy, sum_x],
                  [sum_xy, sum_y2, sum_y],
                  [sum_x, sum_y, n]])
    B = np.array([sum_xz, sum_yz, sum_z])

    # 求解线性方程组
    result = np.linalg.solve(A, B)
    a = result[0] / 2
    b = result[1] / 2
    c = -result[2]
    print(f"方程组的解: {a}, {b}, {c}")
    r = np.sqrt(a ** 2 + b ** 2 - c)

    return a, b, r

# 示例数据
# x = np.array([1, 2, 3, 4, 5])
# y = np.array([2, 3, 4, 5, 6])
x = np.array([1,0,-1])
y = np.array([0,1,0])

# 进行圆拟合
a, b, r = circle_fit(x, y)
print(f"圆心坐标: ({a}, {b})")
print(f"半径: {r}")